import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from CloudGuardian.models import BindRelationship
from SecureHelperServer.settings import formatResponseData
from utils.conf import Response
from utils.custom import MyJWTAuthentication


class RemoveBindRelationship(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        云监护-解除监护关系
        """
        data = copy.deepcopy(formatResponseData)
        try:
            wardUserUid = request.data.get("wardUserUid")

            if not wardUserUid:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            user = request.user

            bindRelationship = BindRelationship.objects.filter(wardUser_id=wardUserUid, guardianUser=user).first()

            if not bindRelationship:
                return Response(data=data, responseMsg="监护关系不存在",
                                loggerMsg=f"云监护-解除监护关系：监护关系不存在，guardianUserUid={user.uid}，wardUserUid={wardUserUid}",
                                isError=True)

            # 解除监护关系
            bindRelationship.delete()

            return Response(data=data, responseMsg="解除成功",
                            loggerMsg=f"云监护-解除监护关系: 解除成功，bindRelationshipId={bindRelationship.id}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
